package org.exez.modules.visitor.util;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.exez.common.util.DateUtils;
import org.exez.modules.visitor.constant.Enum;
import org.exez.modules.visitor.entity.WhiteList;
import org.exez.modules.visitor.service.IWhiteListService;
import org.exez.modules.visitor.vo.PolicePayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.util.List;

public class MinaClientHandle extends IoHandlerAdapter {
	
    private final String values;






    public MinaClientHandle(String values) {
        this.values = values;
    }



    @Override
    public void sessionOpened(IoSession session) {
        session.write(values);
    }

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
        try {
            String str = message.toString();
            String channel = session.getServiceAddress().toString();
            String ip = channel.substring(1, channel.indexOf(":"));
            String port = channel.substring(channel.indexOf(":")+1);

            Db.use().findAll("visitor_police_setting");
            List<Entity> mongDbUrl = Db.use().findAll(Entity.create("visitor_police_setting").set("id", "1"));
            String url = "";
            if(mongDbUrl.size() > 0){
                Entity entity = mongDbUrl.get(0);
                url = entity.get("url").toString();
            }
            if(str.contains("userInfoModify")){
                Db.use().findAll("visitor_police_pay");
                List<Entity> all = Db.use().findAll(Entity.create("visitor_police_pay").set("ip", ip)
                        .set("port", port));
                if(all.size() > 0 ){
                    Entity entity = all.get(0);
                    int is_scan = Integer.parseInt(entity.get("is_scan").toString());
                    String institution_id = entity.get("institution_id").toString();
                    String pay_id = entity.get("pay_id").toString();
                    String secret = entity.get("secret").toString();
                    String create_by = entity.get("create_by").toString();
                    String update_by = entity.get("update_by").toString();

                    JSONObject object = JSON.parseObject(str);
                    JSONObject object1 = JSON.parseObject(object.getString("data"));
                    String inFlag = object1.getString("inFlag");
                    String name = object1.getString("name");
                    String idCard = object1.getString("idCard");
                    String photo = object1.getString("headImg").replaceAll("\r|\n", "");
                    if("1".equals(inFlag)){//在职
                        WhiteList whiteList = new WhiteList();
                            String code = "";
                            code = UploadUtil.upload(url, photo);
                            whiteList.setFacePhoto(code);
                            whiteList.setCreateTime(DateUtils.getDate());
                            whiteList.setInstitutionId(Integer.parseInt(institution_id));
                            whiteList.setIdentityValue(idCard);
                            whiteList.setIdentityType(1);
                            whiteList.setWhiteName(name);
                            whiteList.setWhiteMobile("");
                            whiteList.setCreateBy(update_by);
                            whiteList.setUpdateBy(update_by);
                            //iWhiteListService.insertWhite(whiteList);
                            insert(whiteList);
                    }
                    if("2".equals(inFlag)){//离职
                        updateWhite(institution_id, idCard);
                    }
                }
            }
            if(str.contains("getUserInfo")){
                Db.use().findAll("visitor_police_pay");
                List<Entity> all = Db.use().findAll(Entity.create("visitor_police_pay").set("ip", ip)
                        .set("port", port));
            if(all.size() > 0 ){
                Entity entity = all.get(0);
                int is_scan = Integer.parseInt(entity.get("is_scan").toString());
                String institution_id = entity.get("institution_id").toString();
                String pay_id = entity.get("pay_id").toString();
                String secret = entity.get("secret").toString();
                String create_by = entity.get("create_by").toString();
                String update_by = entity.get("update_by").toString();


                    JSONObject object = JSON.parseObject(str);
                    JSONObject object1 = JSON.parseObject(object.getString("data"));
                    String temp = object1.getString("users");
                    int total = Integer.parseInt(object1.getString("total"));
                    int pageIndex = Integer.parseInt(object1.getString("pageIndex"));

                    List<PolicePayVO> list = JSONObject.parseArray(temp,PolicePayVO.class);
                    for (int i = 0; i < list.size(); i++) {
                        PolicePayVO policePayVO = list.get(i);
                        policePayVO.setHeadImg(policePayVO.getHeadImg().replaceAll("\r|\n", ""));
                        if(is_scan == 0){
                            System.out.println(policePayVO.getName());
                            System.out.println(policePayVO.getIdCard());
                            System.out.println("处理图片");
                            WhiteList whiteList = new WhiteList();
                            String code = "";
                            code = UploadUtil.upload(url, policePayVO.getHeadImg());
                            if(code.length() > 7|| code .equals("123")){
                                whiteList.setFacePhoto(code);
                                whiteList.setCreateTime(DateUtils.getDate());
                                whiteList.setInstitutionId(Integer.parseInt(institution_id));
                                whiteList.setIdentityValue(policePayVO.getIdCard());
                                whiteList.setIdentityType(1);
                                whiteList.setWhiteName(policePayVO.getName());
                                whiteList.setWhiteMobile("");
                                whiteList.setCreateBy(update_by);
                                whiteList.setUpdateBy(update_by);
                                //iWhiteListService.insertWhite(whiteList);
                                insert(whiteList);
                            }
                        }
                    }
                    int now = pageIndex*Integer.parseInt(Enum.PolicePayNum.getName());
                    if(now < total){
                        getConnectAnd(ip, Integer.parseInt(port), pay_id, secret,pageIndex+1);
                    }
                    if(list.size() != Integer.parseInt(Enum.PolicePayNum.getName())){
                        update(ip);
                    }
                }
            }else {
                System.out.println("客户端接收到="+str);
            }

            //PolicePay policePay = iPolicePayService.selectPolicePayByIpAndPort(ip, port);


        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void insert(WhiteList whiteList) throws SQLException {
        if(selectWhite(whiteList)){
            Db.use().insertForGeneratedKey(
                    Entity.create("visitor_white_list")
                            .set("face_photo", whiteList.getFacePhoto())
                            .set("institution_id", whiteList.getInstitutionId())
                            .set("white_name", whiteList.getWhiteName())
                            .set("identity_value", whiteList.getIdentityValue())
                            .set("identity_type", 1)
                            .set("create_time", whiteList.getCreateTime())
                            .set("update_time", whiteList.getCreateTime())
                            .set("white_mobile", whiteList.getWhiteMobile())
                            .set("create_by", whiteList.getCreateBy())
                            .set("update_by", whiteList.getUpdateBy())
                            .set("deleted", 2)
            );
        }
    }

    public void update(String ip) throws SQLException {
        Db.use().update(
                Entity.create().set("is_scan", 1), //修改的数据
                Entity.create("visitor_police_pay").set("ip", ip) //where条件
        );
    }

    public void updateWhite(String dw,String idcard) throws SQLException {
        Db.use().update(
                Entity.create().set("deleted", 3), //修改的数据
                Entity.create("visitor_white_list").set("institution_id", dw).set("identity_value", idcard) //where条件
        );
    }

    public boolean selectWhite(WhiteList whiteList) throws SQLException {
        List<Entity> all = Db.use().findAll(Entity.create("visitor_white_list").set("identity_value", whiteList.getIdentityValue()));
        if(all.size() == 0){
            return true;
        }else {
            return false;
        }
    }

    public boolean getConnectAnd(String ip,int port,String payId,String secret,int pageIndex){
        // TODO Auto-generated method stub
        IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(30000);
        TextLineCodecFactory lineCodec=new TextLineCodecFactory(Charset.forName("UTF-8"));
        lineCodec.setDecoderMaxLineLength(1024*1024*1024); //1G
        lineCodec.setEncoderMaxLineLength(1024*1024*1024); //1G
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(lineCodec));
        //String payId="1001";
        //String secret="002f0c86af67473aa280c8d5ef165a19";
        JSONObject json=new JSONObject();
        json.put("method", "connectCheck");
        JSONObject data=new JSONObject();
        long time=System.currentTimeMillis();
        data.put("payId", payId);
        data.put("time", time);
        try {
            data.put("sign", MD5.md5(secret+time));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        json.put("data", data);
        connector.setHandler(new MinaClientHandle(json.toString()));
        //ConnectFuture dd=connector.connect(new InetSocketAddress("122.228.181.162", 9999));
        ConnectFuture dd=connector.connect(new InetSocketAddress(ip, port));

        if(dd == null){
            return false;
        }
        try {
            Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            if(dd.getSession() == null){
                dd=connector.connect(new InetSocketAddress(ip, port));
                Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            }
            if(dd.getSession() == null){
                dd=connector.connect(new InetSocketAddress(ip, port));
                Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            }
            if(dd.getSession() == null){
                dd=connector.connect(new InetSocketAddress(ip, port));
                Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            }
            if(dd.getSession() == null){
                dd=connector.connect(new InetSocketAddress(ip, port));
                Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            }
            if(dd.getSession() == null){
                dd=connector.connect(new InetSocketAddress(ip, port));
                Thread.sleep(Integer.parseInt(Enum.PolicePayTime.getName()));
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        json=new JSONObject();
        json.put("method", "getUserInfo");
        data=new JSONObject();
        data.put("pageIndex", pageIndex);
        data.put("pageSize", Enum.PolicePayNum.getName());
        json.put("data", data);
        IoSession ii  = dd.getSession();
        ii.write(json.toString());
        return true;
    }

    public int allPage (int total){
        if(total%90 == 0){
            return total/90;
        }else {
            return total/90 + 1;
        }
    }
    
}
